//
//  LocationUnit.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/23.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import CoreLocation

class LocationUnit: NSObject {
     
    var longitude: String { get { return _longitude } }
    
    var latitude: String { get { return _latitude } }
    
    private var _longitude: String = "0"
    private var _latitude: String = "0"
    
    private let manager = CLLocationManager()
    private let geocoder = CLGeocoder()
    
    var takeOnce = false
    var taked = false
    
    var settingClosure: () -> () = { }
    var addressRefuseClosure: () -> () = { }
    var addressUpdate: (String) -> () = {_ in}
    var addressLine = ""
    var showLoading = false
    
    func startLocation() {
        manager.delegate = self

        let state = CLLocationManager.authorizationStatus()
        switch state {
        case .authorizedAlways, .authorizedWhenInUse:
            setupLocation()
        case .notDetermined:
            manager.requestWhenInUseAuthorization()
        default :
            showError()
        }
    }
    
    deinit {
        print("LocationUnit   ---   deinit")
    }
    
    private func setupLocation() {
        if showLoading {
            APPHud.shared.showLoading(text: "正在获取您的位置".localized)
        }
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter = kCLDistanceFilterNone
        manager.startUpdatingLocation()
    }
    
    func showError() {
        APPHud.shared.dismiss()
        let alert = UIAlertController.init(title: "系统提示".localized, message: "请在iPhone的\"设置\"中，允许AE Solar访问你的位置。".localized, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "取消".localized, style: .cancel, handler: { [weak self] (_) in
            self?.addressRefuseClosure()
        }))
        alert.addAction(UIAlertAction.init(title: "设置".localized, style: .default, handler: { [weak self] (_) in
            self?.settingClosure()
            guard let url = URL.init(string: UIApplication.openSettingsURLString) else { return }
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }))
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
    func geocodeLocation(_ address: String, success: @escaping (String, String) -> ()) {
        geocoder.geocodeAddressString(address, in: nil, preferredLocale: nil) { (placemarks, error) in
            guard let placemark = placemarks?.first,
            let longitude = placemark.location?.coordinate.longitude,
            let latitude = placemark.location?.coordinate.latitude else { return }
            success("\(longitude)", "\(latitude)")
        }
    }
}

extension LocationUnit: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .authorizedAlways, .authorizedWhenInUse:
            setupLocation()
        case .notDetermined: break
        default :
            showError()
            _longitude = ""
            _latitude = ""
            addressLine = ""
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }
        
        geocoder.reverseGeocodeLocation(location) { [weak self] (placemarks, error) in
            if let _ = error {
                APPHud.shared.dismiss()
                self?.addressRefuseClosure()
                return
            }
            guard let placemark = placemarks?.first,
                let addressLines = placemark.addressDictionary?["FormattedAddressLines"] as? [String],
                let addressLine = addressLines.first,
                let self = self else { return }
            
            guard !(self.takeOnce && self.taked) else {
                manager.stopUpdatingHeading()
                return
            }
            self.taked = true
            APPHud.shared.dismiss()
            self._longitude = "\(location.coordinate.longitude)"
            self._latitude = "\(location.coordinate.latitude)"
            self.addressLine = addressLine
            self.addressUpdate(addressLine)
        }
    }
    
}
